package cn.maxxieyi.aichatbot.holder;

import cn.maxxieyi.aichatbot.config.ChatBotConfig;
import cn.maxxieyi.aichatbot.enums.AiTypeEnum;
import cn.zhouyafeng.itchat4j.Wechat;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;


/**
 * 存储 AiService 实例
 */
@Getter
@Component
public class ItchatHolder {

    @Resource
    private ChatBotConfig chatBotConfig;

    @Autowired
    private AiApiServiceHolder aiApiServiceHolder;

    private Wechat wechat;


    /**
     * 初始化 itchat
     */
    @PostConstruct
    public void init() {
        File qrPath = new File(chatBotConfig.getQrPath());
        if (!qrPath.exists()) {
            qrPath.mkdirs();
        }
        // 实现IMsgHandlerFace接口的类
        IMsgHandlerFace msgHandler = null;
        if(AiTypeEnum.GMORE_AI.getType().equals(chatBotConfig.getAiType())){
            msgHandler = new ItchatGmoreAiMsgHander(aiApiServiceHolder.getService(chatBotConfig.getAiType()), chatBotConfig.getAiApiKey());
        }else if(AiTypeEnum.LINK_AI.getType().equals(chatBotConfig.getAiType())){
            msgHandler = new ItchatLinkAiMsgHander(aiApiServiceHolder.getService(chatBotConfig.getAiType()), chatBotConfig.getAiApiKey(), chatBotConfig.getAiApiToken());
        }else if(AiTypeEnum.TULING_ROBOT.getType().equals(chatBotConfig.getAiType())){
            msgHandler = new ItchatTulingRobotMsgHander(aiApiServiceHolder.getService(chatBotConfig.getAiType()), chatBotConfig.getAiApiKey());
        }
        else{
            msgHandler = new ItchatSimpleMsgHander();
        }
        wechat = new Wechat(msgHandler, qrPath.getAbsolutePath()); // 【注入】
        wechat.start(); // 启动服务，会在qrPath下生成一张二维码图片，扫描即可登陆，注意，二维码图片如果超过一定时间未扫描会过期，过期时会自动更新，所以你可能需要重新打开图片

    }

}
